package com.lv.dhart.interceptor;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.lv.dhart.MApplication;
import com.lv.dhart.ui.activity.login.LoginActivity;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Okhttp接口请求拦截器，判断token是否过期，若token过期则跳转至登录页面
 * */
public class TokenInterceptor implements Interceptor {
    private SharedPreferences.Editor editor;
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        response = response.newBuilder()
                .removeHeader("pragma")
                .header("Cache-Control", "max-age=60")
                .build();
        //根据和服务端的约定判断token过期
        if (isTokenExpired(response)) {
            //token过期 跳转到登录页
            Intent intent = new Intent(MApplication.getAppContext(), LoginActivity.class);//LOGIN为注册表里添加
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MApplication.getAppContext().startActivity(intent);
            //清空登录信息
            editor = MApplication.getAppContext().getSharedPreferences("login", Context.MODE_PRIVATE).edit();
            editor.remove("token");
            editor.apply();
        }
        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     */
    private boolean isTokenExpired(Response response) {
        Log.i("TOKENAPP",response.code()+"123");
        if (response.code() ==-401||response.code()==401) {
            return true;
        }
        return false;
    }
}
